package com.chineseall.app;

import java.util.Set;
import java.util.concurrent.ConcurrentMap;

import jmind.core.collect.FixedArrayBlockingQueue;
import jmind.core.support.LogUtil;

import com.chineseall.app.pojo.mongo.MMessage;
import com.chineseall.app.ws.SendMessage;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;

/**
 * 群聊管理
 * @author wbxie
 * 2013-12-25
 */
public class ChatManager {

    public static final ChatManager INSTANCE = new ChatManager();

    private final SetMultimap<Integer, Integer> chats;

    private final ConcurrentMap<Integer, FixedArrayBlockingQueue<MMessage>> messages = Maps.newConcurrentMap();

    private ChatManager() {
        SetMultimap<Integer, Integer> map = HashMultimap.create();
        chats = Multimaps.synchronizedSetMultimap(map);
        //        ArrayListMultimap<Integer, MMessage> mess = ArrayListMultimap.create();
        //        messages = Multimaps.synchronizedListMultimap(mess);

    }

    public void add(Integer groupId, Integer uid) {
        chats.put(groupId, uid);

    }

    public Set<Integer> getGroup(int groupId) {
        return chats.get(groupId);
    }

    public void remove(Integer groupId, Integer uid) {
        chats.remove(groupId, uid);
    }

    public FixedArrayBlockingQueue<MMessage> getGroupMessage(int groupId) {
        FixedArrayBlockingQueue<MMessage> message = messages.get(groupId);
        if (message == null) {
            message = new FixedArrayBlockingQueue<MMessage>(10);
            messages.put(groupId, message);
        }
        return message;
    }

    public void sends(int groupId, MMessage data) {
        getGroupMessage(groupId).add(data);
        Set<Integer> set = chats.get(groupId);
        LogUtil.debug(groupId + "set={}", set);
        for (Integer uid : set) {
            boolean b = SendMessage.send(uid, data);
            if (!b) {
                chats.remove(groupId, uid);
            }
        }

    }
}
